// Create a token without the client
const jwt = require('jsonwebtoken');
const axios = require('axios');

// Admin API key goes here
const key = '60b20426a310c187dc811e7d:409fac5f488163d8229834c3c9755cdacf958dd4fa53539c8f0049da799815a8';

// Split the key into ID and SECRET
const [id, secret] = key.split(':');

// Create the token (including decoding secret)
const token = jwt.sign({}, Buffer.from(secret, 'hex'), {
    keyid: id,
    algorithm: 'HS256',
    expiresIn: '5m',
    audience: `/v3/admin/`
});

const host = 'http://isxb.picp.net/g'
// Make an authenticated request to create a post
const url = host + '/ghost/api/v3/admin/posts?source=html';
const headers = { Authorization: `Ghost ${token}` };

function post2Ghost(post) {
	const payload = { posts: [post] };
	return axios.post(url, payload, { headers })
	    // .then(response => console.log('------post-------', response.data.posts[0], '-------------'))
	    .catch(error => console.error(error));
}

function putGhost(id, post) {
    const payload = { posts: [post] };
    return axios.put(host + '/ghost/api/v3/admin/posts/' + id, payload, { headers })
        // .then(response => console.log('------put-------', response.data.posts[0], '-------------'))
        .catch(error => console.error(error));
}

module.exports = { post2Ghost, putGhost };